package app.server.project.main.service.db.entity.user;

import app.server.project.core.constants.Def;
import app.server.project.core.syndb.SynDBMgr;
import app.server.project.core.util.MathUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Transient;
import lombok.Data;
import org.hibernate.annotations.Comment;

import java.time.LocalDateTime;

@Data
@Entity(name = "user_rank")
@TableName("user_rank")
@Comment(value = "用户排行榜信息表")
public class UserRankEntity {

    @Id
    @Column(name = "id")
    @Comment("用户主键")
    @TableId("id")
    private long id;


    @Column(name = "user_id")
    @Comment("用户主键")
    @TableField("user_id")
    private long userId;

    @TableField("rank_id")
    @Comment("排行榜id")
    @Column(name = "rank_id")
    private int rankId;

    @TableField("val")
    @Comment("数值")
    @Column(name = "val")
    private long val;
    @TableField("create_time")
    @Comment("创建时间")
    @Column(name = "create_time")
    private LocalDateTime createTime;

    @Transient
    @TableField(exist = false)
    private boolean synDb = false;

    public static UserRankEntity of(long userId, int rankId, long id) {
        UserRankEntity userInfoEntity = new UserRankEntity();
        userInfoEntity.setId(id);
        userInfoEntity.setSynDb(true);
        userInfoEntity.setUserId(userId);
        userInfoEntity.setRankId(rankId);
        userInfoEntity.setCreateTime(LocalDateTime.now());
        return userInfoEntity;
    }

    public void setUserId(long userId) {
        this.userId = userId;
        if (!this.synDb) return;
        SynDBMgr.addChangeData(UserRankEntity::getUserId, this);
    }

    public void setRankId(int rankId) {
        this.rankId = rankId;
        if (!this.synDb) return;
        SynDBMgr.addChangeData(UserRankEntity::getRankId, this);
    }

    public void setVal(long val) {
        this.val = val;
        if (!this.synDb) return;
        SynDBMgr.addChangeData(UserRankEntity::getVal, this);
    }

    public void addVal(long val) {
        var ret = MathUtil.canAddNum(this.val, val);
        this.setVal(this.val + ret);
    }

    public void consumeVal(long val) {
        if (this.val >= val) {
            this.val -= val;
        } else {
            this.val = Def.Zero;
        }
        this.setVal(this.val);
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
        if (!this.synDb) return;
        SynDBMgr.addChangeData(UserRankEntity::getCreateTime, this);
    }


}
